package com.ruoyi.utils.msg;

import cn.hutool.core.lang.Console;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.service.ISysConfigService;

import java.util.ArrayList;
import java.util.List;

/**
 * 企业微信消息通知类
 */
public class QyWxWebhookUtils {

    private static ISysConfigService configService = SpringUtils.getBean(ISysConfigService.class);

    public static AjaxResult sendMsg(String title,List<JSONObject> contentList){
        String qywxReqUri = configService.selectConfigByKey("qy.wx.req.uri");
        if(StringUtils.isBlank(qywxReqUri)){
            return AjaxResult.error("企业微信机械人配置地址有误！");
        }
        HttpRequest request = new HttpRequest(qywxReqUri);
        request.header("Content-Type", "application/json");
        request.method(Method.POST);
        //拼接请求参数
        JSONObject paramJson = new JSONObject();
        paramJson.set("msgtype", "markdown");
        //拼接出content
        StringBuilder contentTxt = new StringBuilder();
        contentTxt.append(title+"\n");
        //循环拼接内容
        for (JSONObject jsonObject : contentList) {
            contentTxt.append(jsonObject.getStr("labelName")+"："+"<font color='"+jsonObject.getStr("color")+"'>"+jsonObject.getStr("txt")+"</font>\n");
        }
        JSONObject contentJson = new JSONObject();
        contentJson.set("content", contentTxt.toString());
        paramJson.set("markdown", contentJson);
        //赋值请求参数
        Console.log(JSONUtil.toJsonStr(paramJson));
        request.body(JSONUtil.toJsonStr(paramJson));
        //发起请求
        HttpResponse response = request.execute();
        if(response.getStatus() == 200){
            JSONObject resObj = JSONUtil.parseObj(response.body());
            if(resObj.getInt("errcode") == 0){
                return AjaxResult.success("消息返送成功！");
            }else{
                return AjaxResult.error(resObj.getStr("errmsg"));
            }
        }
        return AjaxResult.error("未知错误！");
    }
}
